﻿using UnityEngine;
using System.Collections;
using AssetLoad;
public class AssetLoadHelper : MonoBehaviour
{
    private AssetBundleManager bundleManager;
    // Use this for initialization
    void Start()
    {
        bundleManager = AssetBundleManager.Instance;
    }
     
    void Awake()
    {
        instance = this;
    }

    private IEnumerator _SetTextureAsync(UITexture texture, string bundleName, bool makeFate)
    {
        bundleManager.LoadAssetBundle(bundleName);
        while (!bundleManager.IsLoadedAssetBundle(bundleName))
        {
            yield return 1;
        }
        if (texture != null)
        {
            texture.mainTexture = bundleManager.GetAssetFromBundle(bundleName,
                CommonMethod.GetAssetNameFromAssetBundleName(bundleName), typeof(Texture2D)) as Texture2D;
            if (makeFate)
            {
                texture.MakePixelPerfect();
            }
        }
    }


    public void SetTextureAsync(UITexture texture, string bundleName, bool makeFate)
    {
        StartCoroutine(_SetTextureAsync(texture, bundleName, makeFate));
    }

    public void UnloadBundle(string bundleName)
    {
        bundleManager.UnloadAssetBundle(bundleName);
    }

    public void LoadAssetAsync(string path, string assetName,System.Type type, System.Action<Object> action)
    {
        StartCoroutine(_LoadAssetAsync(path, assetName, type, action));
    }

    private IEnumerator _LoadAssetAsync(string path, string assetName, System.Type type, System.Action<Object> action)
    {
        bundleManager.LoadAssetBundle(path);
        while (!bundleManager.IsLoadedAssetBundle(path))
        {
            yield return 1;
        }
        Object obj = bundleManager.GetAssetFromBundle(path, assetName, type);
        if (obj != null)
        {
            obj = Instantiate(obj);
            action(obj);
        }
    }
    
    private static AssetLoadHelper instance;
    public static AssetLoadHelper Instance
    {
        get
        {
            return instance;
        }
    }
}
